<template>
    <teleport to="body">
        <transition name="a-dialog-fade">
            <div v-if="modelValue" class="a-dialog-mask" @click="close()" @mousedown="handleMouseDown"
                @mousemove="handleMouseMove" @mouseup="handleMouseUp" @contextmenu.prevent.stop="">
                <div class="a-dialog" @click.stop="" :class="onShake ? 'shake' : ''">
                    <div style="display: block;">
                        <slot></slot>
                    </div>
                </div>
            </div>
        </transition>
    </teleport>
</template>
<script>
export default {
    name: "a-a-dialog"
}
</script>
<script setup>
import { defineEmits, ref, defineProps, watch, onUnmounted } from 'vue'
const props = defineProps({
    modelValue: {
        type: Boolean,
        default: false
    },
    shake: {
        type: Boolean,
        default: false
    },
    maskClose: {
        type: Boolean,
        default: true
    }
})

const isClick = ref(false);
const isDragging = ref(false);
const emit = defineEmits(['update:modelValue', "close"])

const visible = ref(props.modelValue);
const onShake = ref(props.shake);

// 鼠标按下时触发
const handleMouseDown = (e) => {
    // 只处理左键点击
    if (e.button !== 0) return;
    isClick.value = true;
};

// 鼠标移动时触发
const handleMouseMove = (e) => {
    if (!isClick.value) return;
    isDragging.value = true;
};

// 鼠标松开时触发
const handleMouseUp = (e) => {
    if (!isClick.value) return;
    setTimeout(() => {
        isClick.value = false;
        isDragging.value = false;
    }, 200);
};

watch(() => props.modelValue, (newVal) => {
    visible.value = newVal;
}, { immediate: true });

watch(() => props.shake, (newVal) => {
    onShake.value = newVal;
}, { immediate: true });


const close = () => {
    if (!props.maskClose || isDragging.value) {
        return;
    }
    emit('update:modelValue', false)
    emit('close')
}
// 在组件销毁时清理
onUnmounted(() => {
    isClick.value = false;
    isDragging.value = false;
});
</script>

<style lang="less" scoped>
@keyframes shake {
    0% {
        transform: translateX(0);
    }

    25% {
        transform: translateX(-5px);
    }

    50% {
        transform: translateX(5px);
    }

    75% {
        transform: translateX(-5px);
    }

    100% {
        transform: translateX(0);
    }
}

.shake {
    animation: shake 0.3s ease-in-out;
}
</style>